﻿using JuCloudy.Framework.Storge;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace JuCloudy.App.Toursim.Root.ctrls
{
    public partial class Create : UserControl
    {
        public Create()
        {
            InitializeComponent();

            this.Loaded += (obj, e) =>
            {
                this.OnLoad();

            };
        }

        private AppDataService.AppToursimProduct ProductEntity { get; set; }
        private void OnLoad()
        {
            this.block_maincontent.Visibility = Visibility.Collapsed;
            this.maincontentpanel.Visibility = Visibility.Collapsed;
            this.block_plans.Visibility = Visibility.Collapsed;
            this.planpanel.Visibility = Visibility.Collapsed;
            this.planctrlpanel.Visibility = Visibility.Collapsed;

            Session.Client["DURAIN"] = String.Empty;
            Session.Client["ACPrice"] = String.Empty;
            Session.Client["ASPrice"] = String.Empty;
            Session.Client["CCPrice"] = String.Empty;
            Session.Client["CSPrice"] = String.Empty;
            Session.Client["CreateTitle"] = String.Empty;
            Session.Client["CreateExplan"] = String.Empty;

            this.com_GoDate.SelectionChanged += (obj, e) =>
            {
                if (e.AddedItems != null && e.AddedItems.Count > 0)
                {
                    this.txt_GoDate.Text = ((ComboBoxItem)e.AddedItems[0]).Content.ToString();
                }
            };

            this.com_Partner.SelectionChanged += (obj, e) =>
            {
                if (e.AddedItems != null && e.AddedItems.Count > 0)
                {
                    this.txt_Partner.Text = ((ComboBoxItem)e.AddedItems[0]).Content.ToString();
                }
            };

            this.com_GroupType.SelectionChanged += (obj, e) =>
            {
                if (e.AddedItems != null && e.AddedItems.Count > 0)
                {
                    this.txt_GroupType.Text = ((ComboBoxItem)e.AddedItems[0]).Content.ToString();
                }
            };

            this.com_GoTraffic.SelectionChanged+=(obj,e)=>{
                if (e.AddedItems != null && e.AddedItems.Count > 0)
                {
                    this.txt_GoTraffic.Text = ((ComboBoxItem)e.AddedItems[0]).Content.ToString();
                }
            };

            this.com_ReTraffic.SelectionChanged += (obj, e) =>
            {
                if (e.AddedItems != null && e.AddedItems.Count > 0)
                {
                    this.txt_ReTraffic.Text = ((ComboBoxItem)e.AddedItems[0]).Content.ToString();
                }
            };

            txt_Durain.TextChanged += (obj, e) =>
            {
                var param = Session.Client["DURAIN"].ToString();
                Decimal res = 0;
                Decimal.TryParse(this.txt_Durain.Text, out res);
                if (!Decimal.TryParse(this.txt_Durain.Text, out res) || res>30)
                {
                    this.txt_Durain.Text = param;
                    this.txt_Durain.SelectionStart = this.txt_Durain.Text.Length;
                }
                else
                {
                    Session.Client["DURAIN"] = this.txt_Durain.Text;
                }
            };

            this.txt_ACPrice.TextChanged += (obj, e) =>
            {
                string param = Session.Client["ACPrice"].ToString();
                Decimal res = 0;
                Decimal.TryParse(this.txt_ACPrice.Text, out res);
                if (!Decimal.TryParse(this.txt_ACPrice.Text, out res))
                {
                    this.txt_ACPrice.Text = param;
                    this.txt_ACPrice.SelectionStart = this.txt_ACPrice.Text.Length;
                }
                else
                {
                    Session.Client["ACPrice"] = this.txt_ACPrice.Text;
                }
            };

            this.txt_ASPrice.TextChanged += (obj, e) =>
            {
                string param = Session.Client["ASPrice"].ToString();
                Decimal res = 0;
                Decimal.TryParse(this.txt_ASPrice.Text, out res);
                if (!Decimal.TryParse(this.txt_ASPrice.Text, out res))
                {
                    this.txt_ASPrice.Text = param;
                    this.txt_ASPrice.SelectionStart = this.txt_ASPrice.Text.Length;
                }
                else
                {
                    Session.Client["ASPrice"] = this.txt_ASPrice.Text;
                }
            };

            this.txt_CCPrice.TextChanged += (obj, e) =>
            {
                string param = Session.Client["CCPrice"].ToString();
                Decimal res = 0;
                Decimal.TryParse(this.txt_CCPrice.Text, out res);
                if (!Decimal.TryParse(this.txt_CCPrice.Text, out res))
                {
                    this.txt_CCPrice.Text = param;
                    this.txt_CCPrice.SelectionStart = this.txt_CCPrice.Text.Length;
                }
                else
                {
                    Session.Client["CCPrice"] = this.txt_CCPrice.Text;
                }
            };

            this.txt_CSPrice.TextChanged += (obj, e) =>
            {
                var param = Session.Client["CSPrice"].ToString();
                Decimal res = 0;
                Decimal.TryParse(this.txt_CSPrice.Text, out res);
                if (!Decimal.TryParse(this.txt_CSPrice.Text, out res))
                {
                    this.txt_CSPrice.Text = param;
                    this.txt_CSPrice.SelectionStart = this.txt_CSPrice.Text.Length;
                }
                else
                {
                    Session.Client["CSPrice"] = this.txt_CSPrice.Text;
                }
            };

            this.txt_Title.TextChanged += (obj, e) =>
            {
                var param = Session.Client["CreateTitle"].ToString();
                if (this.txt_Title.Text.Length>27)
                {
                    this.txt_Title.Text = param;
                    this.txt_Title.SelectionStart = this.txt_Title.Text.Length;
                }
                else
                {
                    Session.Client["CreateTitle"] = this.txt_Title.Text;
                    this.txt_TitleLength.Text = String.Format("当前已输入{0}字，剩余{1}字", this.txt_Title.Text.Length.ToString(),(27-this.txt_Title.Text.Length).ToString());
                }
            };

            this.txt_Explan.TextChanged += (obj, e) =>
            {
                var param = Session.Client["CreateExplan"].ToString();
                if (this.txt_Explan.Text.Length > 200)
                {
                    this.txt_Explan.Text = param;
                    this.txt_Explan.SelectionStart = this.txt_Explan.Text.Length;
                }
                else
                {
                    Session.Client["CreateExplan"] = this.txt_Explan.Text;
                    this.txt_explanLength.Text = String.Format("当前已输入{0}字，剩余{1}字", this.txt_Explan.Text.Length.ToString(), (200 - this.txt_Explan.Text.Length).ToString());
                }
            };
        }

        private void btn_AddPerDayPlan_Click(object sender, RoutedEventArgs e)
        {
            if (this.planpanel.Children != null && this.planpanel.Children.Count > 0)
            {
                this.planpanel.Children.Add(new PerDayPlan(this.planpanel.Children.Count + 1));
            }
            else
            {
                this.planpanel.Children.Add(new PerDayPlan(1));
            }
        }

        private void btn_DelPerDayPlan_Click(object sender, RoutedEventArgs e)
        {
            if (this.planpanel.Children != null && this.planpanel.Children.Count > 0)
            {
                this.planpanel.Children.Remove(this.planpanel.Children[this.planpanel.Children.Count - 1]);
            }
        }


        public String GetProductType()
        {
            var query = from c in this.ProductTypePanel.Children
                        where ((RadioButton)c).IsChecked == true
                        select c;
            if(query!=null&&query.Count()>0)
            {
                return ((JuCloudy.Platform.UserControls.jRadioButton)query.ToList()[0]).Content.ToString();
            }
            else
            {
                return null;
            }
        }

        public string GetPlanType()
        {
            var query = from c in this.PlanTypePanel.Children
                        where ((RadioButton)c).IsChecked == true
                        select c;
            if (query != null && query.Count() > 0)
            {
                return ((JuCloudy.Platform.UserControls.jRadioButton)query.ToList()[0]).Content.ToString();
            }
            else
            {
                return null;
            }
        }

        private void btn_next_Click(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(this.txt_Departure.Text) &&
                            !String.IsNullOrEmpty(this.txt_Destination.Text) &&
                            !String.IsNullOrEmpty(this.txt_Durain.Text) &&
                            !String.IsNullOrEmpty(this.txt_Partner.Text) &&
                            !String.IsNullOrEmpty(this.txt_ReTraffic.Text) &&
                            !String.IsNullOrEmpty(this.txt_GoTraffic.Text) &&
                            !String.IsNullOrEmpty(this.GetPlanType()) &&
                            !String.IsNullOrEmpty(this.GetProductType()))
            {
                //写入数据库
                /*ExService.ExServiceSoapClient ProductClient = new ExService.ExServiceSoapClient(
                    String.Format("http://{0}/ApiService/App/Toursim/ProductService.asmx", Framework.Storge.VariableHelper.WebServiceHost));*/
                AppDataService.AppDataContext ctx = new AppDataService.AppDataContext(new Uri(String.Format("http://{0}/ApiService/AppDataService.svc", Framework.Storge.VariableHelper.WebServiceHost)));
                AppDataService.AppToursimProduct product = new AppDataService.AppToursimProduct()
                {
                    CreateBy = JuCloudy.Framework.Storge.VariableHelper.UserId,
                    Departure = this.txt_Departure.Text,
                    Destination = this.txt_Destination.Text,
                    Durain = this.txt_Durain.Text,
                    GoTraf = this.txt_GoTraffic.Text,
                    PartnerId = 0,
                    PartnerName = "NOSET",
                    PlanType = GetPlanType(),
                    ProductType = GetProductType(),
                    ReTraf = this.txt_ReTraffic.Text,
                    CreateDate = DateTime.Now
                };
                ctx.AddToToursimProduct(product);
                JuCloudy.Framework.Storge.VariableHelper.Structure.ShowLoading();
                ctx.BeginSaveChanges(System.Data.Services.Client.SaveChangesOptions.Batch, new AsyncCallback((r) =>
                {
                    JuCloudy.Framework.Storge.VariableHelper.Structure.CloseLoading();
                    ctx.EndSaveChanges(r);
                    ProductEntity = product;
                    //创建详细行程框
                    int totalDays = int.Parse(this.txt_Durain.Text);
                    this.planpanel.Children.Clear();
                    for (int i = 0; i < totalDays; i++)
                    {
                        this.planpanel.Children.Add(new PerDayPlan(i + 1));
                    }

                    //生成参考标题
                    String traf = "";
                    if (this.txt_GoTraffic.Text == "旅游巴士" || this.txt_ReTraffic.Text == "旅游巴士")
                    {
                        traf = "大巴";
                    }
                    else if (this.txt_GoTraffic.Text == "火车" || this.txt_ReTraffic.Text == "火车")
                    {
                        traf = "火车";
                    }
                    else if (this.txt_GoTraffic.Text == this.txt_ReTraffic.Text)
                    {
                        if (this.txt_GoTraffic.Text == "动车/高铁")
                        {
                            traf = "双动";
                        }
                        else if (this.txt_GoTraffic.Text == "飞机")
                        {
                            traf = "双飞";
                        }
                        else if (this.txt_GoTraffic.Text == "轮船")
                        {
                            traf = "双船";
                        }
                    }
                    else if (this.txt_GoTraffic.Text == "飞机" && this.txt_ReTraffic.Text == "动车/高铁")
                    {
                        traf = "飞动";
                    }
                    else if (this.txt_GoTraffic.Text == "动车/高铁" && this.txt_ReTraffic.Text == "飞机")
                    {
                        traf = "动飞";
                    }
                    else if (this.txt_GoTraffic.Text == "轮船" && this.txt_ReTraffic.Text == "飞机")
                    {
                        traf = "船飞";
                    }
                    else if (this.txt_GoTraffic.Text == "飞机" && this.txt_ReTraffic.Text == "轮船")
                    {
                        traf = "飞船";
                    }

                    this.txt_Title.Text = String.Format("{0}至{1}{2}{3}日{4}", this.txt_Departure.Text, this.txt_Destination.Text, traf, this.txt_Durain.Text, GetPlanType());

                    this.block_maincontent.Visibility = Visibility.Visible;
                    this.maincontentpanel.Visibility = Visibility.Visible;
                    this.block_plans.Visibility = Visibility.Visible;
                    this.planpanel.Visibility = Visibility.Visible;
                    this.planctrlpanel.Visibility = Visibility.Visible;
                }), null);
            }
        }

        private List<JuCloudy.Data.Entity.AppEntity.PlanEntity> GetEntities()
        {
            var entities = new List<JuCloudy.Data.Entity.AppEntity.PlanEntity>();
            foreach(var item in this.planpanel.Children)
            {
                if(item is PerDayPlan)
                {
                    entities.Add(((PerDayPlan)item).GetEntity());
                }
            }
            return entities;
        }

        private void btn_Submit_Click(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(this.txt_ACPrice.Text) &&
                !String.IsNullOrEmpty(this.txt_ASPrice.Text) &&
                !String.IsNullOrEmpty(this.txt_CCPrice.Text) &&
                !String.IsNullOrEmpty(this.txt_CSPrice.Text) &&
                !String.IsNullOrEmpty(this.txt_Explan.Text) &&
                !String.IsNullOrEmpty(this.txt_Title.Text) &&
                !String.IsNullOrEmpty(this.txt_GroupType.Text) &&
                !String.IsNullOrEmpty(this.txt_GoDate.Text) &&
                this.txt_StartDate.SelectedDate!=null&&
                this.txt_EndDate.SelectedDate!=null&&
                
                GetEntities() != null)
            {

                AppDataService.AppDataContext ctx = new AppDataService.AppDataContext(new Uri(String.Format("http://{0}/ApiService/AppDataService.svc", Framework.Storge.VariableHelper.WebServiceHost)));

                var content = new AppDataService.AppToursimContent()
                {
                    AcPrice = Decimal.Parse(this.txt_ACPrice.Text),
                    AsPrice = Decimal.Parse(this.txt_ASPrice.Text),
                    CcPrice = Decimal.Parse(this.txt_CCPrice.Text),
                    CsPrice = Decimal.Parse(this.txt_CSPrice.Text),
                    CreateBy = JuCloudy.Framework.Storge.VariableHelper.UserId,
                    CreateDate = DateTime.Now,
                    EndDate = this.txt_EndDate.SelectedDate,
                    Explan = this.txt_Explan.Text,
                    GoDate = this.txt_GoDate.Text,
                    GroupType = this.txt_GroupType.Text,
                    ProductId = ProductEntity.ProductId,
                    StartDate = this.txt_StartDate.SelectedDate,
                    Title = this.txt_Title.Text
                };


                var itinerary = new AppDataService.AppToursimItinerary()
                {
                    CreateBy = JuCloudy.Framework.Storge.VariableHelper.UserId,
                    CreateDate = DateTime.Now,
                    Detial = GetEntities().Serialize(),
                    ProductId = ProductEntity.PartnerId
                };
                ctx.AddToToursimContent(content);
                ctx.AddToToursimItinerary(itinerary);
                JuCloudy.Framework.Storge.VariableHelper.Structure.ShowLoading();
                ctx.BeginSaveChanges(new AsyncCallback((r) => 
                {
                    ctx.EndSaveChanges(r);
                    JuCloudy.Framework.Storge.VariableHelper.Structure.CloseLoading();
                    MessageBox.Show("Success!");
                }), null);

            }
            else { }
        }

        
    }
}
